/**
 * Language services and color providers for ArenaNext
 * Handles syntax highlighting, color providers, and compiler options
 */

import { errorsToIgnore } from "./editorActions";

/**
 * Registers color providers for GameRGBColor and GameRGBAColor
 * @param {Object} monacoController - The Monaco controller instance
 */
export function registerColorProviders(monacoController) {
  const monaco = monacoController.monacoController.monaco;

  // Register color provider for GameRGBColor and GameRGBAColor
  monaco.languages.registerColorProvider("javascript", {
    provideColorPresentations: (document, colorInfo) => {
      let red = colorInfo.color.red.toFixed(2);
      let green = colorInfo.color.green.toFixed(2);
      let blue = colorInfo.color.blue.toFixed(2);
      let alpha = colorInfo.color.alpha.toFixed(2);
      let label;

      if (document.getValueInRange(colorInfo.range).includes("GameRGBAColor")) {
        label = `new GameRGBAColor(${red},${green},${blue},${alpha})`;
      } else {
        label = `new GameRGBColor(${red},${green},${blue})`;
      }

      return [{ label }];
    },

    provideDocumentColors: (document) => {
      const colorInfos = [];

      document
        .getValue()
        .split("\n")
        .forEach((line, index) => {
          const colorRegex = /new\s+(?:GameRGBColor|GameRGBAColor)\(([^)]*)\)/g;
          let match;

          while ((match = colorRegex.exec(line)) !== null) {
            let arg = match[1].split(",");
            const red = Number(arg[0] ?? 0);
            const green = Number(arg[1] ?? 0);
            const blue = Number(arg[2] ?? 0);
            const alpha = arg.length === 4 ? Number(arg[3]) : 1;
            const color = { red, blue, green, alpha };

            const range = new monacoController.monacoController.monaco.Range(
              index + 1,
              match.index + 1,
              index + 1,
              match.index + match[0].length + 1
            );

            colorInfos.push({ color, range });
          }
        });

      return colorInfos;
    },
  });

  // Register color provider for Vec3.create
  monaco.languages.registerColorProvider("javascript", {
    provideColorPresentations: (document, colorInfo) => {
      let red = Math.round(colorInfo.color.red * 255);
      let green = Math.round(colorInfo.color.green * 255);
      let blue = Math.round(colorInfo.color.blue * 255);
      let label = `Vec3.create({r:${red},g:${green},b:${blue}})`;

      return [{ label }];
    },

    provideDocumentColors: (document) => {
      const colorInfos = [];

      document
        .getValue()
        .split("\n")
        .forEach((line, index) => {
          const colorRegex = /Vec3.create\(([^)]+)\)/g;
          let match;

          while ((match = colorRegex.exec(line)) !== null) {
            const rMatch = match[0].match(/r:\s*(\d+)/);
            const gMatch = match[0].match(/g:\s*(\d+)/);
            const bMatch = match[0].match(/b:\s*(\d+)/);

            if (!rMatch || !gMatch || !bMatch) {
              continue;
            }

            const red = rMatch ? parseInt(rMatch[1], 10) / 255 : 0;
            const green = gMatch ? parseInt(gMatch[1], 10) / 255 : 0;
            const blue = bMatch ? parseInt(bMatch[1], 10) / 255 : 0;
            const alpha = 1;
            const color = { red, blue, green, alpha };

            const range = new monacoController.monacoController.monaco.Range(
              index + 1,
              match.index + 1,
              index + 1,
              match.index + match[0].length + 1
            );

            colorInfos.push({ color, range });
          }
        });

      return colorInfos;
    },
  });
}

/**
 * Sets up enhanced JavaScript compiler options for better IDE experience
 * @param {Object} monacoController - The Monaco controller instance
 */
export async function setupJavaScriptOptions(monacoController) {
  const monaco = monacoController.monacoController.monaco;

  const diagnosticsOptions = {
    noSemanticValidation: false,
    noSyntaxValidation: false,
    diagnosticCodesToIgnore: errorsToIgnore,
  };
  // 为TypeScript设置诊断选项
  monaco.languages.typescript.typescriptDefaults.setDiagnosticsOptions(
    diagnosticsOptions
  );

  // 为JavaScript设置诊断选项
  monaco.languages.typescript.javascriptDefaults.setDiagnosticsOptions(
    diagnosticsOptions
  );

  const editor = unsafeWindow.editObk;

  if (editor) {
    // 添加对Peek Definition的支持
    editor.updateOptions({
      cursorBlinking: "smooth", // 启用平滑光标闪烁
      cursorSmoothCaretAnimation: "on", // 启用平滑光标动画
      //quickSuggestions: true, // 启用快速建议
      suggestOnTriggerCharacters: true, // 在触发字符后显示建议
      acceptSuggestionOnEnter: "on", // 按Enter键接受建议
      tabCompletion: "on", // 启用Tab补全
      snippetSuggestions: "top", // 代码片段显示在顶部
      mouseWheelZoom: true, // 允许鼠标滚轮缩放
      glyphMargin: true, // 启用字形边距
      suggest: {
        showIcons: true, // 显示建议图标
        showStatusBar: true, // 显示状态栏
        preview: true, // 启用建议预览
        previewMode: "prefix", // 预览模式
        selectionMode: "always", // 选择模式
        filterGraceful: true, // 优雅过滤
        showDeprecated: true, // 显示过时
      },
      // 增强导航和定义查找功能
      gotoLocation: {
        multiple: "peek", // 如果有多个定义，显示peek视图
        multipleDefinitions: "peek",
        multipleTypeDefinitions: "peek",
        multipleDeclarations: "peek",
        multipleImplementations: "peek",
        multipleReferences: "peek",
      },
      // 定义链接选项
      definitionLinkOpensInPeek: true, // 点击定义链接时打开peek视图而不是跳转
    });

    // 监听模型变化，自动设置语言
    editor.onDidChangeModel((e) => {
      const model = editor.getModel();
      if (!model) return;

      const uri = model.uri.toString();
      if (uri.endsWith(".ts") || uri.endsWith(".tsx")) {
        // 设置为TypeScript
        monaco.editor.setModelLanguage(model, "typescript");
      } else if (uri.endsWith(".js") || uri.endsWith(".jsx")) {
        // 设置为JavaScript
        monaco.editor.setModelLanguage(model, "javascript");
      }
    });

    // 为当前模型设置语言
    const currentModel = editor.getModel();
    if (currentModel) {
      const uri = currentModel.uri.toString();
      if (uri.endsWith(".ts") || uri.endsWith(".tsx")) {
        monaco.editor.setModelLanguage(currentModel, "typescript");
      } else if (uri.endsWith(".js") || uri.endsWith(".jsx")) {
        monaco.editor.setModelLanguage(currentModel, "javascript");
      }
    }
  }

  // 获取当前编译选项
  const currentOptions =
    monaco.languages.typescript.javascriptDefaults.getCompilerOptions();

  const enhancedPaths = {
    // 直接通过名称导入（无路径前缀）
    "*": ["*", "/*.js", "./*.js", "/server/*.js", "/client/*.js"],

    // 相对路径导入（带./前缀）
    "./*": ["*", "/*.js", "./*.js", "/server/*.js", "/client/*.js"],

    // 绝对路径导入（带/前缀）
    "/*": ["*", "/*.js", "./*.js", "/server/*.js", "/client/*.js"],

    // 确保明确带.js扩展名的导入也能正常工作
    "*.js": ["*", "/*.js", "./*.js", "/server/*.js", "/client/*.js"],
    "./*.js": ["*", "/*.js", "./*.js", "/server/*.js", "/client/*.js"],
    "/*.js": ["*", "/*.js", "./*.js", "/server/*.js", "/client/*.js"],
  };

  // 启用高级JavaScript语言功能
  const compilerOptions = {
    ...currentOptions,
    target: monaco.languages.typescript.ScriptTarget.ESNext,
    module: monaco.languages.typescript.ModuleKind.ESNext,
    moduleResolution: monaco.languages.typescript.ModuleResolutionKind.NodeJs,
    allowNonTsExtensions: true,
    allowJs: true,
    paths: enhancedPaths,
    lib: [],
    resolveJsonModule: true,
    noEmit: true,
    esModuleInterop: true,
    allowSyntheticDefaultImports: true,
  };
  // 启用高级JavaScript语言功能
  monaco.languages.typescript.javascriptDefaults.setCompilerOptions(
    compilerOptions
  );

  // 配置TypeScript编译器选项
  monaco.languages.typescript.typescriptDefaults.setCompilerOptions(
    compilerOptions
  );
}

/**
 * Sets up custom syntax highlighting theme for JavaScript code
 * @param {Object} monacoController - The Monaco controller instance
 */
export function setupCustomJavaScriptTheme(monacoController) {
  try {
    const monaco = monacoController.monacoController.monaco;
    const editorInstance = monacoController.monacoController.monacoEditor;

    // 配置编辑器选项以支持括号对着色
    editorInstance.updateOptions({
      inlineSuggest: {
        enabled: true,
        mode: "subword", // 设置为 subword 模式，更智能的补全
        showToolbar: "always", // 总是显示工具栏
      },
      // 启用默认括号对着色
      bracketPairColorization: {
        enabled: true,
      },
      guides: {
        bracketPairs: "active", // 仅显示活动括号对
        bracketPairsHorizontal: "active", // 仅为活动对显示水平指南
        highlightActiveBracketPair: true,
        indentation: true,
      },
      formatOnPaste: true,
      formatOnType: true,
      folding: true,
    });
    const tokenConfig = {
      tokenizer: {
        root: [
          // VS Code风格的语法高亮

          // 注释 - 优先处理注释避免干扰其他匹配
          [/\/\/.*$/, "comment"],
          [/\/\*\*/, "comment.jsdoc", "@jsdoc"], // 捕获JSDoc注释
          [/\/\*/, "comment", "@comment"],

          // 字符串 - 提前处理避免内部关键字误匹配
          [/"([^"\\]|\\.)*"/, "string"],
          [/'([^'\\]|\\.)*'/, "string"],
          [/`/, "string", "@templateString"],

          // 操作符 - 在关键字前处理避免干扰
          [/[=+\-*%&|^!~<>?:]+/, "operator"],
          [/\/(?![\/\*])/, "operator"], // 除法操作符，但不是注释开始

          // 关键字分组 - 紫色关键字 (控制流和模块相关)
          [
            /\b(if|else|for|while|do|switch|case|default|break|continue|return|try|catch|finally|throw|yield|await|import|export|from|as)\b/,
            "keyword.control",
          ],

          // 蓝色关键字 (声明和其他关键字)
          [
            /\b(var|let|const|function|class|extends|implements|constructor|get|set|static|async|new|this|super|typeof|instanceof|void|delete|in|of|with)\b/,
            "keyword.declaration",
          ],

          // 布尔值、null和undefined (蓝色)
          [/\b(true|false|null|undefined|NaN|Infinity)\b/, "keyword.other"],

          // 内置对象和类型 (青色)
          [
            /\b(Object|Array|String|Number|Boolean|RegExp|Map|Set|Promise|Date|Math|JSON|Error|Symbol|BigInt|WeakMap|WeakSet|Proxy|Reflect|Int\d+Array|Float\d+Array|Uint\d+Array)\b(?!\s*:)/,
            "support.class",
          ],

          // 变量声明语句后的变量名 (浅蓝色)
          [
            /\b(var|let|const)\s+([a-zA-Z_$][\w$]*)/,
            ["keyword.declaration", "variable.declaration"],
          ],

          // 函数声明后的函数名 (金黄色)
          [
            /\bfunction\s+([a-zA-Z_$][\w$]*)/,
            ["keyword.declaration", "entity.name.function.declaration"],
          ],

          // 类声明后的类名 (青色)
          [
            /\bclass\s+([A-Z][a-zA-Z0-9_$]*)/,
            ["keyword.declaration", "entity.name.class.declaration"],
          ],

          // 函数调用 - 普通函数调用 (金黄色)
          [/(?<!\.)([a-z_$][\w$]*)(?=\s*\()/, "entity.name.function"],

          // 方法调用 - 带点符号的方法调用 (金黄色)
          [
            /(\.)([a-z_$][\w$]*)(?=\s*\()/,
            ["delimiter", "entity.name.function"],
          ],

          // 全大写的属性访问 (.BOTAA 但不是 .COLOR_LUcsTc) - 深蓝色
          [
            /(\.)([A-Z][A-Z0-9_]*)(?![A-Z0-9_]*_[a-z])\b(?!\s*\()/,
            ["delimiter", "constant.uppercase"],
          ],

          // 对象属性访问 - 带点符号的属性访问 (浅蓝色)
          [
            /(\.)([a-zA-Z_$][\w$]*)(?!\s*\()/,
            ["delimiter", "variable.property"],
          ],

          // 类名和接口名 - 首字母大写 (青色)
          [/\b([A-Z][a-zA-Z0-9_$]*)(?!\s*:)/, "entity.name.class"],

          // 常量 - 全大写带下划线 (亮蓝色)
          [/\b([A-Z][A-Z0-9_$]+)\b/, "variable.other.constant"],

          // 属性名和对象键 (浅蓝色)
          [/([a-zA-Z_$][\w$]*)\s*:/, "variable.property"],

          // 参数定义中的变量 (浅蓝色)
          [/(?<=\()([a-zA-Z_$][\w$]*)\s*(?=[,)])/, "variable.parameter"],

          // 数字字面量 (浅绿色)
          [/\b\d+(\.\d+)?([eE][+-]?\d+)?\b/, "constant.numeric"],
          [/\b0[xX][0-9a-fA-F]+\b/, "constant.numeric.hex"],
          [/\b0[bB][01]+\b/, "constant.numeric.binary"],
          [/\b0[oO][0-7]+\b/, "constant.numeric.octal"],

          // 正则表达式 (红色)
          [/\/(?![\/\*])(?:[^\/\\]|\\.)+\/[gimsuy]*/, "regexp"],

          // 分隔符和标点符号
          [/[{}()\[\]]/, "delimiter.bracket"],
          [/[;,.]/, "delimiter"],

          // 其他标识符 (变量名等) - 必须放在最后作为兜底
          [/[a-zA-Z_$][\w$]*/, "variable.other"],
        ],

        // 多行注释
        comment: [
          [/[^/*]+/, "comment"],
          [/\*\//, "comment", "@pop"],
          [/[/*]/, "comment"],
        ],

        // JSDoc注释
        jsdoc: [
          // JSDoc结束标记
          [/\*\//, "comment.jsdoc", "@pop"],

          // JSDoc标签
          [/@\w+/, "comment.jsdoc.tag"],

          // JSDoc类型
          [/\{/, "comment.jsdoc.bracket", "@jsdoctype"],

          // 其他JSDoc文本
          [/[^@*{]+/, "comment.jsdoc"],
          [/./, "comment.jsdoc"],
        ],

        // JSDoc类型定义
        jsdoctype: [
          // 处理嵌套的大括号
          [/\{/, "comment.jsdoc.bracket", "@jsdoctypeBracket"],
          [/\}/, "comment.jsdoc.bracket", "@pop"],
          [/[^{}]+/, "comment.jsdoc.type"],
        ],

        // 处理JSDoc类型中嵌套的大括号
        jsdoctypeBracket: [
          [/\{/, "comment.jsdoc.bracket", "@jsdoctypeBracket"],
          [/\}/, "comment.jsdoc.bracket", "@pop"],
          [/[^{}]+/, "comment.jsdoc.type"],
        ],

        // 模板字符串处理
        templateString: [
          [/[^`$\\]+/, "string"],
          [/\$\{/, "delimiter.bracket", "@templateExpr"],
          [/\\./, "string.escape"],
          [/`/, "string", "@pop"],
        ],

        // 模板字符串中的表达式
        templateExpr: [
          [/\}/, "delimiter.bracket", "@pop"],
          { include: "root" },
        ],
      },
    };
    // 设置完整的语法标记提供者
    monaco.languages.setMonarchTokensProvider("javascript", tokenConfig);
    monaco.languages.setMonarchTokensProvider("typescript", tokenConfig);

    // 定义VS Code风格的主题
    monaco.editor.defineTheme("customJsTheme", {
      base: "vs-dark",
      inherit: true,
      rules: [
        // 注释 - 绿灰色
        { token: "comment", foreground: "#6A9955" },

        // JSDoc注释 - 特殊颜色
        { token: "comment.jsdoc", foreground: "#6A9955" }, // 基础JSDoc颜色
        {
          token: "comment.jsdoc.tag",
          foreground: "#569CD6",
          fontStyle: "bold",
        }, // 蓝色加粗
        { token: "comment.jsdoc.type", foreground: "#4EC9B0" }, // 青色
        { token: "comment.jsdoc.param", foreground: "#9CDCFE" }, // 浅蓝色
        { token: "comment.jsdoc.bracket", foreground: "#FFD700" }, // 金色括号

        // 字符串 - 橙红色
        { token: "string", foreground: "#CE9178" },
        { token: "string.escape", foreground: "#D7BA7D" },

        // 关键字 - 蓝色/紫色
        { token: "keyword.declaration", foreground: "#569CD6" }, // 蓝色关键字
        { token: "keyword.control", foreground: "#C586C0" }, // 紫色关键字
        { token: "keyword.other", foreground: "#569CD6" }, // 蓝色关键字
        { token: "delimiter.bracket", foreground: "#569CD6" },

        // 类名/类型 - 青色
        { token: "entity.name.class", foreground: "#4EC9B0" },
        { token: "entity.name.class.declaration", foreground: "#4EC9B0" },
        { token: "support.class", foreground: "#4EC9B0" },

        // 函数和方法 - 金黄色
        { token: "entity.name.function", foreground: "#DCDCAA" },
        { token: "entity.name.function.declaration", foreground: "#DCDCAA" },

        // 变量 - 区分变量和属性的颜色
        { token: "variable.declaration", foreground: "#4FC1FF" }, // 声明的变量名
        { token: "variable.parameter", foreground: "#4FC1FF" }, // 参数变量名
        { token: "variable.other", foreground: "#4FC1FF" }, // 普通变量名
        { token: "variable.other.constant", foreground: "#4FC1FF" }, // 常量变量名
        { token: "constant.uppercase", foreground: "#4fc1ff" }, // 全大写属性

        // 对象属性 - 浅蓝色 (VS Code风格)
        { token: "variable.property", foreground: "#9CDCFE" }, // 属性名/键名

        // 数字 - 浅绿色
        { token: "constant.numeric", foreground: "#B5CEA8" },
        { token: "constant.numeric.hex", foreground: "#B5CEA8" },
        { token: "constant.numeric.binary", foreground: "#B5CEA8" },
        { token: "constant.numeric.octal", foreground: "#B5CEA8" },

        // 正则表达式 - 红色
        { token: "regexp", foreground: "#D16969" },

        // 操作符和分隔符 - 白色
        { token: "operator", foreground: "#D4D4D4" },
        { token: "delimiter", foreground: "#D4D4D4" },
      ],
      colors: {
        "editor.foreground": "#D4D4D4",
        "editor.background": "#1E1E1E",
        "editorCursor.foreground": "#AEAFAD",
        "editor.lineHighlightBackground": "#2C323C30",
        "editorLineNumber.foreground": "#858585",
        "editor.selectionBackground": "#264F78",
        "editor.inactiveSelectionBackground": "#3A3D41",
        "editorIndentGuide.background": "#404040",
        "editorIndentGuide.activeBackground": "#707070",
        // 括号对颜色
        "editorBracketPairGuide.activeBackground1": "#FF00FFAA", // 亮洋红
        "editorBracketPairGuide.activeBackground2": "#00FFFDAA", // 亮青色
        "editorBracketPairGuide.activeBackground3": "#FFA500AA", // 橙色
        "editorBracketPairGuide.activeBackground4": "#00FF00AA", // 亮绿色
        "editorBracketPairGuide.activeBackground5": "#FF0000AA", // 亮红色
        "editorBracketPairGuide.activeBackground6": "#FFFF00AA", // 亮黄色
      },
    });
    // 应用主题
    monaco.editor.setTheme("customJsTheme");

    // 注册JSDoc @标签补全
    monaco.languages.registerCompletionItemProvider("javascript", {
      triggerCharacters: ["@"],
      provideCompletionItems: function (model, position) {
        const lineContent = model.getLineContent(position.lineNumber);
        // 判断是否在JSDoc注释内（简单判断：当前行为 * 开头且前面有 /**）
        const textUntilPosition = model.getValueInRange({
          startLineNumber: Math.max(1, position.lineNumber - 10),
          startColumn: 1,
          endLineNumber: position.lineNumber,
          endColumn: position.column,
        });
        // 只在注释块内触发
        if (
          !/\/\*\*([\s\S]*?)\*\//.test(textUntilPosition) &&
          !/^\s*\*/.test(lineContent)
        ) {
          return { suggestions: [] };
        }
        const jsdocTags = [
          {
            name: "param",
            description: "描述函数或方法的参数。",
            example: "@param {string} name - 用户的名称。",
          },
          {
            name: "returns",
            description: "描述函数的返回值。",
            example: "@returns {number} - 计算结果。",
          },
          {
            name: "return",
            description: "描述函数的返回值（同 @returns）。",
            example: "@return {boolean} - 操作是否成功。",
          },
          {
            name: "type",
            description: "定义变量或属性的类型。",
            example: "@type {Object}",
          },
          {
            name: "typedef",
            description: "定义一个自定义类型。",
            example:
              "@typedef {Object} User - 用户对象类型\n@property {string} id - 用户ID\n@property {string} username - 用户名",
          },
          {
            name: "property",
            description: "描述对象的属性（常与 @typedef 配合使用）。",
            example: "@property {string} name - 属性名称。",
          },
          {
            name: "template",
            description: "声明一个模板参数，用于泛型。",
            example: "@template T",
          },
          {
            name: "deprecated",
            description: "标记一个方法或属性已废弃。",
            example:
              "@deprecated oldMethod将在 v2.0.0 中移除，请改用 newMethod。",
          },
          {
            name: "private",
            description: "标记成员为私有。",
            example: "@private",
          },
          {
            name: "protected",
            description: "标记成员为受保护。",
            example: "@protected",
          },
          {
            name: "public",
            description: "标记成员为公共（默认）。",
            example: "@public",
          },
          {
            name: "readonly",
            description: "标记属性为只读。",
            example: "@readonly",
          },
          {
            name: "see",
            description: "引用其他相关的文档或资源。",
            example: "@see {@link otherFunction}",
          },
          {
            name: "example",
            description: "提供一个代码示例。",
            example:
              "@example \n<caption>示例标题</caption>\n// 示例代码\nfunction greet(name) {\n  return 'Hello, ' + name;\n}",
          },
          {
            name: "throws",
            description: "描述函数可能抛出的错误。",
            example: "@throws {Error} 当输入无效时。",
          },
          {
            name: "enum",
            description: "定义一个枚举类型。",
            example:
              "@enum {number}\nDirection = {\n  UP: 1,\n  DOWN: -1,\n  LEFT: 2,\n  RIGHT: -2\n};",
          },
          {
            name: "implements",
            description: "指明一个类实现了一个接口。",
            example: "@implements {Printable}",
          },
          {
            name: "extends",
            description: "指明一个类或接口继承自另一个类或接口。",
            example: "@extends {BaseClass}",
          },
          {
            name: "constructor",
            description: "标记一个函数为类的构造函数。",
            example: "@constructor",
          },
          {
            name: "abstract",
            description: "标记一个类或方法为抽象的。",
            example: "@abstract",
          },
          {
            name: "async",
            description: "标记一个函数为异步函数。",
            example: "@async",
          },
          {
            name: "callback",
            description: "定义一个回调函数类型。",
            example:
              "@callback LogCallback\n@param {string} message - 日志信息。",
          },
          {
            name: "default",
            description: "指定一个参数的默认值。",
            example: "@param {string} [name='Guest'] - 名称。",
          },
          {
            name: "description",
            description: "提供一段描述信息。",
            example: "@description 这是一个重要的模块。",
          },
          {
            name: "export",
            description: "标记一个模块或成员被导出。",
            example: "@export",
          },
          {
            name: "external",
            description: "引用一个外部类或模块。",
            example: "@external {jQuery}",
          },
          {
            name: "file",
            description: "提供文件的概述信息。",
            example: "@file 文件描述。",
          },
          {
            name: "fires",
            description: "描述函数可能触发的事件。",
            example: "@fires MyClass#eventName",
          },
          {
            name: "ignore",
            description: "指示文档生成器忽略此部分。",
            example: "@ignore",
          },
          {
            name: "link",
            description: "创建一个链接到其他标识符或URL。",
            example: "{@link MyClass#method}",
          },
          {
            name: "module",
            description: "定义一个JavaScript模块。",
            example: "@module my/module",
          },
          {
            name: "namespace",
            description: "定义一个命名空间。",
            example: "@namespace MyNamespace",
          },
          {
            name: "override",
            description: "标记一个方法覆盖了父类的方法。",
            example: "@override",
          },
          {
            name: "package",
            description: "标记成员属于某个包（已废弃，JSDoc3+中作用不大）。",
            example: "@package my.package",
          },
          {
            name: "requires",
            description: "指定一个模块依赖。",
            example: "@requires module:my/otherModule",
          },
          {
            name: "static",
            description: "标记一个成员为静态的。",
            example: "@static",
          },
          {
            name: "this",
            description: "指定函数中 `this` 关键字的类型。",
            example: "@this {MyClass}",
          },
          {
            name: "version",
            description: "指定库或模块的版本号。",
            example: "@version 1.0.0",
          },
        ];
        return {
          suggestions: jsdocTags.map((tagInfo) => ({
            label: "@" + tagInfo.name,
            kind: monaco.languages.CompletionItemKind.Keyword,
            insertText: "@" + tagInfo.name,
            documentation: tagInfo.description,
            detail: tagInfo.example,
            range: {
              startLineNumber: position.lineNumber,
              startColumn: position.column - 1, //因为我们是在@后触发，所以要替换掉@符号
              endLineNumber: position.lineNumber,
              endColumn: position.column,
            },
            sortText: "0_" + tagInfo.name, // 加个前缀确保排在前面
          })),
        };
      },
    });
  } catch (error) {
    console.error("设置自定义JavaScript主题失败:", error);
  }
}
